using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class GameManager:SingletonManager<GameManager>,ISaveMainManager
{
    //基础数据
    [Header("可以进行操作吗")]
    public bool canOprate = true;
    [Header("玩家")]
    public Player player;
    [Header("此时的楼层")]
    public GameObject currLevelObj;
    public bool isUpStair = false;
    [Header("触发了致命伤害")]
    public bool canHaveHurtEnd = true;
    [Header("正在战斗")]
    public bool isBattle = false;
    [Header("当前存档")]
    public int fileNum = 1;
    [Header("血矛次数")]
    public int bloodNum = 1;
    [Header("是否吃了血果")]
    public bool eatBloodFruit = false;
    //保存数据
    [Header("金币")]
    public float coin = 0;
    [Header("钥匙数量")]
    public int yellowKeyNum = 0;
    public int blueKeyNum = 0;
    public int redKeyNum = 0;
    [Header("到达层级")]
    public bool[] unLockLevel = new bool[100];
    [Header("退出时的楼层")]
    public int quitIdLevel = 0;
    [Header("血月")]
    public bool isBloodMoon = false;
    public float bloodMoonTimer = 90f;//持续90秒
    [Header("怨灵珠")]
    public int circleNum = 0;
    [Header("红符")]
    public int redTurnNum = 0;
    [Header("超脱石")]
    public int stoneNum = 0;
    [Header("生锈钥匙")]
    public int keyNum = 0;
    [Header("希望之花数量")]
    public int wishFlower = 0;
    [Header("篮球数量")]
    public int ballNum = 0;
    [Header("终剑数量")]
    public int finalSwordNum = 0;
    [Header("净化之剑")]
    public bool haveSword = false;
    [Header("是否胜利")]
    public bool isWin = false;
    [Header("是否拯救公主")]
    public bool isSavePro = false;
    [Header("是否杀死公主")]
    public bool isKillPro = false;
    [Header("生成敌人房间数量")]
    public int enemyRoomNum = 0;
    [Header("生成道具房间数量")]
    public int itemRoomNum = 0;
    [Header("生成商店房间数量")]
    public int shopItemRoomNum = 0;
    [Header("死亡数据")]
    public PlayerDieData playerDieData;
    [Header("两个存档")]
    public bool save1 = false;
    public bool save2 = false;

    [Header("守塔人")]
    public GameObject towerMan;

    [Header("事件图片")]//0:太阳，1：血月
    public List<Sprite> eventIcon = new List<Sprite>();

    public void Start()
    {
        ////数据加载
        //SaveManager.instance.LoadMainData(Application.persistentDataPath, "Data"+fileNum+"/MainData");
        //SaveManager.instance.SeekMainDataInterface();
        //SaveManager.instance.GetMainDataInterface();

        //初始化UI驱动,先打开某UI
        PanelManager.Init();
        //打开测试游戏UI
        PanelManager.Open<MainPanel>();
        PanelManager.Open<AchiPanel>();
        //更新一下基础数据
        UpdateMathData();
        //更新框内UI
        UpdateBoundeUI();

        //PanelManager.Open<BlackPanel>(true, true, SceneItemManager.instance.id);

        //默认帧率位60帧
        QualitySettings.vSyncCount=0;
        Application.targetFrameRate=60;
        //适配机型
        OnAssignAndriod();
    }
    private void Update()
    {
        //事件驱动
        EventManager.Update();
        //计算死亡时间
        CalculateDieTimer();
    }
    //适配手机屏幕
    public void OnAssignAndriod()
    {
        float screenW = Screen.width;
        float screenH = Screen.height;
        if(screenH>2100)
        {
            GameObject.Find("Main Camera").GetComponent<Camera>().orthographicSize = 9.5f;
        }
        else
        {
            GameObject.Find("Main Camera").GetComponent<Camera>().orthographicSize = 8.6f;
        }
    }
    //改变怨灵珠
    public void ChangeCircle(int amount)
    {
        circleNum+=amount;

        //更新UI
        UpdateBoundeUI();
    }
    //改变红符
    public void ChangeRedTurn(int amount)
    {
        redTurnNum+=amount;

        //更新UI
        UpdateBoundeUI();
    }
    //改变超脱石
    public void ChangeStone(int amount)
    {
        stoneNum+=amount;

        //更新UI
        UpdateBoundeUI();
    }
    //改变生锈钥匙
    public void ChangeKey(int amount)
    {
        keyNum+=amount;

        //更新UI
        UpdateBoundeUI();
    }
    //改变希望之花
    public void ChangeFlower(int amount)
    {
        wishFlower+=amount;

        //更新UI
        UpdateBoundeUI();
    }
    //改变篮球
    public void ChangeBall(int amount)
    {
        ballNum+=amount;

        //更新UI
        UpdateBoundeUI();
    }
    //改变终剑
    public void ChangeFinalSword(int amount)
    {
        finalSwordNum += amount;

        //更新UI
        UpdateBoundeUI();
    }
    //更新框内UI
    public void UpdateBoundeUI()
    {
        MsgMainBoundle msg = new MsgMainBoundle();
        msg.redTurnNum=redTurnNum;
        msg.circleNum=circleNum;
        msg.keyNum=keyNum;
        msg.stoneNum=stoneNum;
        msg.flowerNum=wishFlower;
        msg.ballNum=ballNum;
        msg.finalSwordNum = finalSwordNum;
        EventManager.AddMsg(msg);
    }
    //金币增加
    public void AddCoin(float amount)
    {
        coin += amount;
        UpdateMathData();
    }
    //金币减少
    public bool ReCoin(int amount)
    {
        if(coin>=amount)
        {
            coin -= amount;
            UpdateMathData();
            return true;
        }
        else
        {

            TipSayManager.Instance.Say("<color=red>金币不足</color>");

            return false;
        }
    }
    //钥匙增加
    public void AddKey(int amount,string str)
    {
        if (str == "黄色") yellowKeyNum += amount;
        else if (str == "蓝色") blueKeyNum += amount;
        else if (str == "红色") redKeyNum += amount;
        UpdateMathData();
    }
    //钥匙减少
    public bool ReKey(int amount,string str)
    {
        if (str == "黄色")
        {
            if (yellowKeyNum < amount) return false;
            yellowKeyNum -= amount;
            UpdateMathData();
            return true;
        }
        else if (str == "蓝色")
        {
            if (blueKeyNum < amount) return false;
            blueKeyNum -= amount;
            UpdateMathData();
            return true;
        }
        else if (str == "红色")
        {
            if (redKeyNum < amount) return false;
            redKeyNum -= amount;
            UpdateMathData();
            return true;
        }
        else if(str=="门")
        {
            if (keyNum < amount) return false;
            ChangeKey(-1);

            //获取撒钱手神器
            if(ArtifactManager.instance.GetArtifact("月星").isHave==false)
            {
                ArtifactManager.instance.AddArtifact("月星");
            }

            return true;
        }

        return false;
    }
    //玩家攻击力
    public void ChangeDamage(int amount)
    {
        player.oriDamage+=amount;
        player.dieDamage+=amount;
        player.dieOriDamage+=amount;
        player.damage=player.oriDamage;

        //更新符文
        TurnManager.instance.UpdateModify();
        //计算此时攻击力

        UpdateMathData();
    }
    //玩家防御力
    public void ChangeArmor(int amount)
    {
        player.oriArmor+=amount;
        player.dieArmor+=amount;
        player.dieOriArmor+=amount;
        player.armor=player.oriArmor;

        //更新符文
        TurnManager.instance.UpdateModify();
        //计算此时的防御

        UpdateMathData();
    }
    //玩家血量
    public void ChangePlayerHp(int amount)
    {
        if(amount>=0)
        {
            player.AddHp(amount);
        }
        else
        {
            player.ReHp(-amount);
        }
        //更新符文
        TurnManager.instance.UpdateModify();

        UpdateMathData();
    }
    //更新基础数据
    public void UpdateMathData()
    {
        MsgMathData msg = new MsgMathData();
        msg.damage=player.damage;
        msg.hp=player.currHp;
        msg.armor=player.armor;
        msg.coin=coin;
        msg.yellowKey=yellowKeyNum;
        msg.blueKey=blueKeyNum;
        msg.redKey=redKeyNum;

        EventManager.AddMsg(msg);
    }
    //更新主名称
    public void UpdateMainName(string str)
    {
        MsgMainName msg = new MsgMainName();
        msg.myName=str;
        EventManager.AddMsg(msg);
    }
    //下一关
    public void NextLevel(bool firEnter)
    {
        int nextId = 0;
        isUpStair = true;
        if (currLevelObj)
        {
            nextId = currLevelObj.GetComponent<SceneItemManager>().id+1;
        }
        if(firEnter)
        {
            nextId=GameManager.Instance.quitIdLevel;
        }
        //卸载当前关卡
        UnloadCurrLevel();
        //加载关卡
        LoadLevel(nextId);
    }
    //加载原楼层
    public void OriLevel(int _id)
    {
        //卸载当前关卡
        UnloadCurrLevel();
        //加载关卡
        LoadLevel(_id);
    }
    //上一关
    public void ForwardLevel()
    {
        int id = 1;
        isUpStair = false;
        if (currLevelObj)
        {
            id = currLevelObj.GetComponent<SceneItemManager>().id - 1;
        }
        //卸载当前关卡
        UnloadCurrLevel();
        //加载关卡
        LoadLevel(id);
    }
    //卸载当前关卡
    public void UnloadCurrLevel()
    {
        //卸载
        if(currLevelObj)
        {
            SaveManager.instance.levelData = null;
            //保存一下当前关卡数据
            SceneItemManager.instance.SaveData();
            if(RandomRoomManager.instance!=null)
            {
                RandomRoomManager.instance.SaveData();
            }
            Destroy(currLevelObj);
            currLevelObj = null;
        }
    }
    //加载关卡
    public void LoadLevel(int id)
    {
        if (id < -1 && id > 100) return;

        //销毁
        UnloadCurrLevel();
        //使用Resources来加载数据
        currLevelObj = Instantiate(ResManager.LoadObj("Level/Level" + id));
        currLevelObj.transform.position = Vector3.zero;
        StartCoroutine(currLevelObj.GetComponent<SceneItemManager>().Init());
        quitIdLevel=id;

        //打开UI
        PanelManager.Open<GamePanel>();

        //运行血月事件
        BloodOfMoonEvent.instance.Init();
        //打开终剑
        player.OpenFinalSword();
    }
    //生成回血数字
    public void CreateAddHpNum(int amount,Vector2 pos)
    {
        GameObject obj = PoolManager.Instance.GetAddHpNum();
        obj.transform.position=pos;
        obj.transform.Find("Text").GetComponent<Text>().text=amount.ToString();
    }
    //生成其他文本
    public void CreateOtherText(string str, Vector2 pos)
    {
        GameObject obj = PoolManager.Instance.GetOtherText();
        obj.transform.position=pos;
        obj.transform.Find("Text").GetComponent<Text>().text=str;
    }
    public void CreateHurtDamage(int damage,Vector2 pos)
    {
        //生成伤害数字
        GameObject obj = PoolManager.Instance.GetDamageNum();
        obj.transform.position = pos;
        obj.transform.Find("Text").GetComponent<Text>().text = damage.ToString();
    }
    //开始战斗
    public void StartBattle(PlayerHurtObj obj,Player player,Enemy enemy)
    {
        if (isBattle) return;
        if (GameManager.Instance.canOprate==false) return;
        StartCoroutine(obj.IAttack(player , enemy));
    }
    //计算死亡时间
    public void CalculateDieTimer()
    {
        if (playerDieData!=null&&player.currHp>0&&playerDieData.isDie&&playerDieData.dieTimer>0)
        {
            playerDieData.dieTimer-=Time.deltaTime;
        }
    }
    //死亡初始化
    public void PlayerDie(Vector2 diePos, int dieLevel)
    {
        //已经死亡，无法再死亡
        if (playerDieData != null && playerDieData.isDie) return;

        PlayerDieData dieData = new PlayerDieData();
        dieData.isDie=true;
        dieData.dieTimer=60;
        dieData.diePos=diePos;
        dieData.levelId=dieLevel;

        playerDieData=dieData;

        //行走幽灵
        if(WaterMapManager.instance!=null)
        {
            WaterMapManager.instance.SetRun();
        }

        PlayerReHalfPlayer();
    }
    //玩家属性减半
    public void PlayerReHalfPlayer()
    {
        if (playerDieData!=null&&playerDieData.isDie)
        {
            player.SetDieData();

            player.damage=Mathf.RoundToInt(player.damage/2);
            player.oriDamage=Mathf.RoundToInt(player.oriDamage/2);
            player.armor=Mathf.RoundToInt(player.armor/2);
            player.oriArmor=Mathf.RoundToInt(player.oriArmor/2);
            player.currHp=Mathf.RoundToInt(player.currHp/2);
            player.oriHp=Mathf.RoundToInt(player.oriHp/2);

            if (player.currHp<=1) player.currHp=1;
            if (player.oriHp<=1) player.oriHp=1;
            if (player.damage<=1) player.damage=1;
            if (player.oriDamage<=1) player.oriDamage=1;
            if (player.armor<=1) player.armor=1;
            if (player.oriArmor<=1) player.oriArmor=1;

            //更新玩家数据
            UpdateMathData();
        }
    }
    //复制文件夹
    public void CopyFile(int fileNum1,int fileNum2)
    {
        //获取存储路径
        string myPath = Application.persistentDataPath;

        string path1Name = "Data"+fileNum1;
        string path2Name = "Data"+fileNum2;

        //开始复制
        bool succ=CopyManager.CopyFileToOtherFile(myPath, path1Name, myPath, path2Name);
    }
    public void Save(ref MainData data)
    {
        if(data==null)
        {
            data=new MainData();
        }

        data.playerCurrHp=player.currHp;
        data.damage=player.damage;
        data.armor=player.armor;
        data.oriArmor=player.oriArmor;
        data.oriDamage=player.oriDamage;
        data.coin=coin;
        data.yellowKeyNum=yellowKeyNum;
        data.redKeyNum=redKeyNum;
        data.blueKeyNum=blueKeyNum;
        data.unLockLevel=unLockLevel;
        data.quitIdLevel=quitIdLevel;
        data.redTurn = redTurnNum;
        data.keyNum = keyNum;
        data.stoneNum = stoneNum;
        data.circleNum = circleNum;
        data.oriHp=player.oriHp;
        data.dogStep=player.dogStep;
        data.sheepStep=player.sheepStep;
        data.haveSword=haveSword;
        data.isWin=isWin;
        data.isNew=false;
        data.bloodMoonTimer=bloodMoonTimer;
        data.isBloodMoon=isBloodMoon;
        data.wishFlower=wishFlower;
        data.ballNum=ballNum;
        data.enemyRoomNum=enemyRoomNum;
        data.itemRoomNum=itemRoomNum;
        data.shopItemRoomNum=shopItemRoomNum;
        data.playerDieData=playerDieData;
        data.dieOriHp=player.dieOriHp;
        data.dieHp=player.dieHp;
        data.dieDamage=player.dieDamage;
        data.dieOriDamage=player.dieOriDamage;
        data.dieArmor=player.dieArmor;
        data.dieOriArmor=player.dieOriArmor;
        data.save1=save1;
        data.save2=save2;
        data.finalSwordNum = finalSwordNum;
        data.isSavePro = isSavePro;
        data.isKillPro = isKillPro;
    }
    public void Load(MainData data)
    {
        if(data!=null&&data.isNew==false)
        {
            player.currHp=data.playerCurrHp;
            player.damage=data.damage;
            player.armor=data.armor;
            player.oriArmor=data.oriArmor;
            player.oriDamage=data.oriDamage;
            coin=data.coin;
            yellowKeyNum=data.yellowKeyNum;
            redKeyNum=data.redKeyNum;
            blueKeyNum=data.blueKeyNum;
            unLockLevel=data.unLockLevel;
            quitIdLevel=data.quitIdLevel;
            redTurnNum = data.redTurn;
            keyNum = data.keyNum;
            stoneNum = data.stoneNum;
            circleNum = data.circleNum;
            player.oriHp=data.oriHp;
            player.dogStep=data.dogStep;
            player.sheepStep=data.sheepStep;
            isWin=data.isWin;
            haveSword=data.haveSword;
            bloodMoonTimer=data.bloodMoonTimer;
            isBloodMoon=data.isBloodMoon;
            wishFlower=data.wishFlower;
            ballNum=data.ballNum;
            enemyRoomNum=data.enemyRoomNum;
            itemRoomNum=data.itemRoomNum;
            shopItemRoomNum=data.shopItemRoomNum;
            playerDieData=data.playerDieData;
            player.dieDamage=data.dieDamage;
            player.dieOriDamage=data.dieOriDamage;
            player.dieArmor=data.dieArmor;
            player.dieOriArmor=data.dieOriArmor;
            player.dieHp=data.dieHp;
            player.dieOriHp=data.dieOriHp;
            save1=data.save1;
            save2=data.save2;
            finalSwordNum = data.finalSwordNum;
            isSavePro = data.isSavePro;
            isKillPro = data.isKillPro;
        }
        else if(data==null||data.isNew)
        {
            //Debug.Log("Data:"+data);
            ClearData();
        }
    }
    //数据清空
    public void ClearData()
    {
        player.currHp=125;
        player.oriHp=player.currHp;
        player.damage=1;
        player.armor=1;
        player.oriArmor=1;
        player.oriDamage=1;
        player.dieDamage=1;
        player.dieOriDamage=1;
        player.dieArmor=1;
        player.dieOriArmor=1;
        player.dieHp=125;
        player.dieOriHp=125;
        coin=0;
        yellowKeyNum=0;
        redKeyNum=0;
        blueKeyNum=0;
        wishFlower=0;
        unLockLevel=new bool[60];
        for (int i = 0; i<60; i++)
        {
            unLockLevel[i]=false;
        }
        quitIdLevel=0;
        stoneNum = 0;
        redTurnNum = 0;
        keyNum = 0;
        circleNum = 0;
        ballNum=0;
        finalSwordNum = 0;
        player.dogStep=0;
        player.sheepStep=0;
        isWin=false;
        haveSword=false;
        bloodMoonTimer=90;
        isBloodMoon=false;
        enemyRoomNum=0;
        itemRoomNum=0;
        shopItemRoomNum=0;
        save1=false;
        save2=false;
        isSavePro = false;
        isKillPro = false;
        playerDieData=new PlayerDieData();

        //进行了数据清空
        Debug.Log("进行了数据清空");
    }
}